package cn.com.qc.leeactivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tandong.sa.tools.AssistTool;
import com.xiang.mail.Mail;
import com.xiang.mail.MailSender;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.qc.R;
import cn.com.qc.app.App;
import cn.com.qc.help.NetUrl;
import cn.com.qc.javabean.IntroInfo;
import cn.com.qc.main.BaseActivity;
import cn.com.qc.main.LoginActivity;
import cn.com.qc.utils.Tools;

/**
 * 职位详情
 */

public class CompanyDetailsActivity extends BaseActivity {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.company)
    TextView company;
    @BindView(R.id.date)
    TextView date;
    @BindView(R.id.location)
    TextView location;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.company2)
    TextView company2;
    @BindView(R.id.trade)
    TextView trade;
    @BindView(R.id.introduce)
    TextView introduce;
    @BindView(R.id.contact)
    TextView contact;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.email)
    TextView email;
    @BindView(R.id.employNum)
    TextView employNum;
    @BindView(R.id.education)
    TextView education;
    @BindView(R.id.jobRequire)
    TextView jobRequire;
    @BindView(R.id.apply)
    Button apply;
    @BindView(R.id.spinner)
    Spinner spinner;
    App app;
    private String id = "";
    private AssistTool assistTool;
    private String localToken = "";
    private String studentId = "";
    private List<String> cv_list;
    private List<String> cv_list_id;
    private List<String> cv_list_name;
    private ArrayAdapter<String> cv_adapter;
    private List<IntroInfo> introInfoList;
    private Integer cv_id = -1;
    private String cv_file = "";
    //发送端
    String FROM_ADD = "1252279088@qq.com";
    //发送端授权密码
    String password = "bwqxigsfeuamjgjd";
    //接收端
    private String send_email = "1252279088@qq.com";
    String[]toAdds = new String[1];
    //职位名称
    private String job_name = "";
    private String company_name = "";
    private String nickname = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_companydetails);
        app = (App) this.getApplication();
        ButterKnife.bind(this);
        Tools.initSystemBarTint(this);
        assistTool = new AssistTool(this);
        localToken = assistTool.getPreferenceString("localToken");
        studentId = assistTool.getPreferenceString("studentId");
        id = getIntent().getStringExtra("id");
        initData();
        GetmyCv();
    }

    @Override
    public void onStart() {
        super.onStart();
        localToken = assistTool.getPreferenceString("localToken");
        studentId = assistTool.getPreferenceString("studentId");
    }

    private void initData() {
        nickname = app.userName;
        OkGo.<String>post(NetUrl.DNS + NetUrl.Jobinfo)
                .tag(this)
                .params("id", id)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            Log.d("详情界面",jsonObject.toString());
                            int infoCode = jsonObject.getInt("status");
                            if (infoCode == 0) {
                                JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                                location.setText("地点：" + jsonObject1.getString("workPlace"));
                               String startTime = jsonObject1.getString("startTime");
                               String endTime = jsonObject1.getString("endTime");
                               String date_text = "日期：";
                               System.out.println(startTime+"和"+endTime);
                               if(startTime!=null&&startTime!=""&&startTime!="null"){
                                   date_text = "日期：" + startTime.substring(0, 10);
                               }
                               if(endTime!=null&&endTime!=""&&endTime!="null"){
                                   date_text = date_text +  " 到 " + endTime.substring(0, 10);
                               }
//                              date.setText("日期：" + Tools.getStrTime(beginDate) + "/" + Tools.getStrTime(endDate));
                                date.setText(date_text);
                                company.setText("公司名称：" + jsonObject1.optString("cname"));
                                company2.setText("公司名称：" + jsonObject1.optString("cname"));
                                trade.setText("行业：" + jsonObject1.optString("professionName"));
                                job.setText("职位名称：" + jsonObject1.optString("title"));
                                contact.setText("联系人：" + jsonObject1.optString("contact"));
                                phone.setText("联系方式：" + jsonObject1.optString("phone"));
                                employNum.setText("招聘人数：" + jsonObject1.optString("employNum"));
                                education.setText("学历：" + jsonObject1.optString("education"));
                                email.setText("邮箱地址：" + jsonObject1.optString("email"));
                                jobRequire.setText(jsonObject1.optString("jobRequire"));
                                introduce.setText(jsonObject1.optString("jobDescribe"));
                                price.setText(jsonObject1.optInt("minMoney") +"-"+jsonObject1.optInt("maxMoney") + "/月");
                                send_email = jsonObject1.optString("email");
                                job_name = jsonObject1.optString("title");
                                company_name = jsonObject1.optString("cname");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @OnClick({R.id.back, R.id.apply})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.apply:
                if (localToken.equals(null) || localToken.equals("") || studentId.equals(null) || studentId.equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    if (cv_id == -1){
                        Tools.toast(CompanyDetailsActivity.this, "您的简历为空，请先上传简历");
                    }else{
                        toAdds[0] = send_email;
                        Log.d("把文件"+cv_file,"发送到"+send_email);
                        final Mail mail = new Mail();
                        mail.setMailServerHost("smtp.qq.com");
                        mail.setMailServerPort("587");
                        mail.setValidate(true);
                        String[] split = FROM_ADD.split("@");
                        mail.setUserName(split[0]); // 你的邮箱地址前一半
                        mail.setPassword(password);// 您的邮箱密码
                        mail.setFromAddress(FROM_ADD); // 发送的邮箱
                        mail.setToAddress(toAdds); // 发到哪个邮件去
                        //mail.setCcAddress(ccAdds);// 抄送邮件
                        //mail.setBccAddress(bccAdds);// 秘密抄送邮件
                        mail.setSubject(company_name+"公司您的职位"+job_name+"有新用户申请"); // 邮件主题
                        mail.setContent(company_name+"公司您好,用户"+nickname+"刚刚申请了您的职位"+job_name+"，简历文件为"+cv_file); // 邮件文本
                        final MailSender mailSender=new MailSender();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                mailSender.sendTextMail(mail);// 记得放子线程
                            }
                        }).start();
                        OkGo.<String>post(NetUrl.DNS + NetUrl.applyJob)
                                .tag(this)
                                .params("JobId", id)
                                .params("cvId", cv_id)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(response.body());
                                            System.out.println("输出结果"+jsonObject);
                                            int infoCode = jsonObject.getInt("status");
                                            if (infoCode == 0) {
                                                Tools.toast(CompanyDetailsActivity.this, "您的申请已提交!");
                                                apply.setBackgroundColor(getResources().getColor(R.color.cc));
                                                apply.setClickable(false);
                                            }else{
                                                String msg = jsonObject.getString("msg");
                                                Tools.toast(CompanyDetailsActivity.this, msg);
                                                apply.setBackgroundColor(getResources().getColor(R.color.cc));
                                                apply.setClickable(false);
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });

                    }
                }
        }
    }
    public void GetmyCv(){
        OkGo.<String>post(NetUrl.DNS + NetUrl.Cvlist)
                .tag(this)
                //.params("WorkPlace", city)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            int infoCode = jsonObject.getInt("status");
                            if (infoCode == 0) {
                                JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                                JSONArray jsonArray = jsonObject1.getJSONArray("records");
                                System.out.println("返回的数据是"+jsonArray);
                                cv_list = new ArrayList<String>();
                                cv_list_id = new ArrayList<String>();
                                cv_list_name = new ArrayList<String>();
                                for (int i = 0;i<jsonArray.length();i++){
                                    JSONObject cv_item = jsonArray.getJSONObject(i);
                                    Integer id = cv_item.optInt("id");
                                    String fileName = cv_item.optString("fileName");
                                    String url =  cv_item.optString("paths")+cv_item.optString("fileId");
                                    cv_list_id.add(id.toString());
                                    cv_list_name.add(fileName);
                                    cv_list.add(url);
                                }
                                //适配器
                                cv_adapter= new ArrayAdapter<String>(CompanyDetailsActivity.this, android.R.layout.simple_spinner_item, cv_list_name);
                                //设置样式
                                cv_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                //加载适配器
                                spinner.setAdapter(cv_adapter);

                                spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {//选择item的选择点击监听事件
                                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                                                               int arg2, long arg3) {
                                        // TODO Auto-generated method stub
                                        // 将所选mySpinner 的值带入myTextView 中
                                        cv_id = Integer.parseInt(cv_list_id.get(arg2));
                                        cv_file = cv_list.get(arg2);
                                        Log.d("选择了", cv_list_id.get(arg2));
                                        Log.d("文件是", cv_list.get(arg2));
                                    }
                                    public void onNothingSelected(AdapterView<?> arg0) {
                                        // TODO Auto-generated method stub
                                        Log.d("选择了", "没选择");
                                    }
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
